import HandleBtn from '@/components/HandleBar/btn';
import type { ActionType, ProColumns, ProFormInstance } from '@/components/Pro/';
import {
  ModalForm,
  ProFormDigit,
  ProFormRadio,
  ProFormText,
  ProFormTreeSelect,
  ProTable,
} from '@/components/Pro/';
import Tabs from '@/components/Tabs';
import {
  sysMenuControllerDelete as deleteFun,
  sysMenuControllerEdit as edit,
  sysMenuControllerPageTreeList as getList,
  sysMenuControllerSave as add,
} from '@/services/ess/sysMenu';
import { sysRoleControllerGetRoleMenus } from '@/services/ess/sysRole';
import { getMenuList } from '@/utils/';
import { message, Modal, Space, Tag } from 'antd';
import React, { useRef, useState } from 'react';
import { getIntl, useIntl } from 'umi';
import Styles from './index.less';

const MenuManagement: React.FC = () => {
  const [currentPlatform, setCurrentPlatform] = useState<'WEB' | 'APP'>('WEB');

  /**
   * @zh-CN 添加节点
   * @param fields
   */
  const handleAdd = async (fields: API.SysMenuForm) => {
    try {
      const res = await add({
        ...fields,
        platformType: currentPlatform,
      });
      if (res.success) {
        message.success(getIntl().formatMessage({ id: 'global.addSuccessfully' }));
      }
      return true;
    } catch (error) {
      message.error(getIntl().formatMessage({ id: 'global.addFailedTips' }));
      return false;
    }
  };

  /** 编辑节点
   * @zh-CN 编辑节点
   * @param fields
   */
  const handleEdit = async (fields: API.SysMenuForm) => {
    try {
      const res = await edit({
        ...fields,
        platformType: currentPlatform,
      });
      if (res.success) {
        message.success(getIntl().formatMessage({ id: 'global.addSuccessfully' }));
        return true;
      }
      return false;
    } catch (error) {
      message.error(getIntl().formatMessage({ id: 'global.addFailedTips' }));
      return false;
    }
  };

  const TableList: React.FC<{ platformType: 'WEB' | 'APP' }> = ({ platformType }) => {
    const [createModalOpen, handleModalOpen] = useState<boolean>(false);

    const actionRef = useRef<ActionType>();
    const formRef = useRef<ProFormInstance>();
    const [currentRow, setCurrentRow] = useState<API.SysMenuForm>({});
    const [menuType, setMenuType] = useState<string | undefined>();
    const intl = useIntl();
    const columns: ProColumns<API.SysMenuForm>[] = [
      {
        title: intl.formatMessage({ id: 'systemManagement.menuManagementMenu.name' }),
        dataIndex: 'name',
        width: 150,
      },
      {
        title: intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.pageUrl' }),
        dataIndex: 'path',
        width: 150,
      },
      {
        title: intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.interfaceUrl' }),
        dataIndex: 'apiUrl',
        width: 150,
      },
      {
        title: intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.permissionFlag' }),
        dataIndex: 'perms',
        width: 150,
      },
      {
        title: intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.type' }),
        dataIndex: 'menuType',
        // valueEnum: {
        //   '0': {
        //     text: '目录',
        //     color: 'blue'
        //   },
        //   '1': {
        //     text: '菜单',
        //     color: 'geekblue'
        //   },
        //   '2': {
        //     text: 'tabs选项卡',
        //     color: 'red'
        //   },
        //   '3': {
        //     text: '按钮',
        //     color: 'orange'
        //   },
        // },
        render: (_, record) =>
          (record.menuType === '0' && (
            <Tag color="blue">
              {intl.formatMessage({ id: 'systemManagement.menuManagementMenu.catalogue' })}
            </Tag>
          )) ||
          (record.menuType === '1' && (
            <Tag color="geekblue">
              {intl.formatMessage({ id: 'systemManagement.menuManagementMenu.menu' })}
            </Tag>
          )) ||
          (record.menuType === '2' && (
            <Tag color="red">
              {intl.formatMessage({ id: 'systemManagement.menuManagementMenu.tabs' })}
            </Tag>
          )) ||
          (record.menuType === '3' && (
            <Tag color="orange">
              {intl.formatMessage({ id: 'systemManagement.menuManagementMenu.button' })}
            </Tag>
          )) ||
          '',
      },
      {
        title: intl.formatMessage({ id: 'systemManagement.menuManagementMenu.sort' }),
        dataIndex: 'menuSort',
      },
      {
        title: intl.formatMessage({ id: 'systemManagement.generalProcedure.operation' }),
        dataIndex: 'option',
        valueType: 'option',
        width: 150,
        render: (_, record) => (
          <Space>
            <a
              key="edit"
              onClick={() => {
                handleModalOpen(true);
                setCurrentRow(record);
                setMenuType(record?.menuType);
              }}
            >
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.edit' })}
            </a>
            {record.menuType === '0' || record.menuType === '1' || record.menuType === '2' ? (
              <a
                key="add"
                onClick={() => {
                  handleModalOpen(true);
                  setCurrentRow({ parentId: record?.menuId });
                }}
              >
                {intl.formatMessage({ id: 'systemManagement.generalProcedure.new' })}
              </a>
            ) : null}
            <a
              key="delete"
              onClick={() => {
                Modal.confirm({
                  title: intl.formatMessage({ id: 'systemManagement.supplementary.prompt' }),
                  content: `数据删除后将不可恢复，是否删除？`,
                  onOk: async () => {
                    const res = await deleteFun([record.menuId], { platformType });
                    if (res.success) {
                      message.success('删除成功');
                      actionRef.current?.reloadAndRest?.();
                    }
                  },
                });
              }}
            >
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.delete' })}
            </a>
          </Space>
        ),
      },
    ];

    return (
      <div>
        <ProTable<API.SysMenu, API.PageParams>
          headerTitle=""
          actionRef={actionRef}
          formRef={formRef}
          rowKey="menuId"
          search={false}
          request={getList}
          params={{
            serviceUser: 0,
            platformType,
          }}
          rowClassName={(record) => {
            if (!record?.routes?.length) {
              console.log(record);
              return Styles.hideExpandIcon;
            }
            return '';
          }}
          expandable={{
            childrenColumnName: 'routes',
          }}
          columns={columns}
          toolBarRender={() => [
            <HandleBtn
              handleType="add"
              key="add"
              onClick={() => {
                setCurrentRow({
                  menuType: '0',
                });
                handleModalOpen(true);
                setMenuType('0');
              }}
            >
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.new' })}
            </HandleBtn>,
          ]}
        />
        <ModalForm
          className={Styles.menuModalForm}
          modalProps={{
            destroyOnClose: true,
          }}
          initialValues={{
            ...currentRow,
            parentId: currentRow?.parentId === '0' ? undefined : currentRow?.parentId?.toString(),
          }}
          title={
            currentRow?.menuId
              ? intl.formatMessage({ id: 'systemManagement.menuManagementMenu.editMenu' })
              : intl.formatMessage({ id: 'systemManagement.menuManagementMenu.addMenu' })
          }
          width={835}
          colProps={{ md: 12 }}
          open={createModalOpen}
          onOpenChange={handleModalOpen}
          onFinish={async (value) => {
            let success;
            //服务对象:内部用户或租户用户
            value.serviceUser = 0;
            value.parentId = value.parentId || '0';
            if (currentRow?.menuId) {
              success = await handleEdit({ ...currentRow, ...value } as API.SysMenuForm);
            } else {
              success = await handleAdd(value as API.SysMenuForm);
            }
            if (success) {
              handleModalOpen(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
        >
          <ProFormTreeSelect
            label={intl.formatMessage({ id: 'systemManagement.menuManagementMenu.superiorMenu' })}
            name="parentId"
            placeholder={intl.formatMessage({
              id: 'remoteUpgradeMangment.siteConfigurationManagement.pleaseChoose',
            })}
            allowClear
            secondary
            request={async () => {
              // Get menu list for the current platform type
              return getMenuList(sysRoleControllerGetRoleMenus, { platformType });
            }}
            fieldProps={{
              fieldNames: {
                label: 'title',
                value: 'key',
                children: 'children',
              },
            }}
          />
          <ProFormRadio.Group
            name="menuType"
            label={intl.formatMessage({ id: 'systemManagement.menuManagementMenu.menuType' })}
            radioType="button"
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'systemManagement.menuManagementMenu.menuType' }),
              },
            ]}
            fieldProps={{
              onChange: (e) => {
                setMenuType(e.target.value);
              },
            }}
            options={[
              {
                label: intl.formatMessage({ id: 'systemManagement.menuManagementMenu.catalogue' }),
                value: '0',
              },
              {
                label: intl.formatMessage({ id: 'systemManagement.menuManagementMenu.menu' }),
                value: '1',
              },
              {
                label: intl.formatMessage({ id: 'systemManagement.menuManagementMenu.tabs' }),
                value: '2',
              },
              {
                label: intl.formatMessage({ id: 'systemManagement.menuManagementMenu.button' }),
                value: '3',
              },
            ]}
          />
          <ProFormText
            name="name"
            label={intl.formatMessage({ id: 'systemManagement.menuManagementMenu.name' })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: 'systemManagement.menuManagementMenu.mustmenuName',
                }),
              },
            ]}
          />
          <ProFormText
            name="path"
            label={intl.formatMessage({ id: 'systemManagement.menuManagementMenu.routingAddress' })}
          />
          <ProFormText
            name="apiUrl"
            label={intl.formatMessage({ id: 'systemManagement.menuManagementMenu.interfaceUrl' })}
          />
          {(menuType === '0' || menuType === '1') && (
            <ProFormText
              name="redirect"
              label={intl.formatMessage({ id: 'systemManagement.menuManagementMenu.redirect' })}
            />
          )}
          {(menuType === '0' || menuType === '1') && (
            <ProFormText
              name="component"
              label={intl.formatMessage({
                id: 'systemManagement.menuManagementMenu.frontEndComponents',
              })}
            />
          )}
          <ProFormText
            name="perms"
            label={intl.formatMessage({
              id: 'systemManagement.menuManagementMenu.permissionFlag',
            })}
          />
          <ProFormDigit
            name="menuSort"
            label={intl.formatMessage({ id: 'systemManagement.menuManagementMenu.sort' })}
          />
          {menuType === '0' && (
            <ProFormText
              name="icon"
              label={intl.formatMessage({ id: 'systemManagement.menuManagementMenu.menuIcons' })}
            />
          )}
          <ProFormRadio.Group
            name="hideChildrenInMenu"
            label={intl.formatMessage({ id: 'systemManagement.menuManagementMenu.hideSubmenus' })}
            radioType="button"
            options={[
              {
                label: intl.formatMessage({ id: 'systemManagement.menuManagementMenu.display' }),
                value: false,
              },
              {
                label: intl.formatMessage({ id: 'systemManagement.menuManagementMenu.hide' }),
                value: true,
              },
            ]}
          />
          <ProFormRadio.Group
            name="hideInMenu"
            label={intl.formatMessage({ id: 'systemManagement.menuManagementMenu.hideMenu' })}
            radioType="button"
            options={[
              {
                label: intl.formatMessage({ id: 'systemManagement.menuManagementMenu.display' }),
                value: false,
              },
              {
                label: intl.formatMessage({ id: 'systemManagement.menuManagementMenu.hide' }),
                value: true,
              },
            ]}
          />
        </ModalForm>
      </div>
    );
  };
  const tabItems = [
    {
      key: 'WEB',
      label: 'WEB 菜单管理',
      children: <TableList platformType="WEB" />,
    },
    {
      key: 'APP',
      label: 'APP 菜单管理',
      children: <TableList platformType="APP" />,
    },
  ];

  return <Tabs items={tabItems} onChange={(key) => setCurrentPlatform(key as 'WEB' | 'APP')} />;
};

export default MenuManagement;
